import React from 'react';
import Alert from '@material-ui/lab/Alert';
import CircularProgress from '@material-ui/core/CircularProgress';
import Dialog from '@material-ui/core/Dialog';
import DialogTitle from '@material-ui/core/DialogTitle';
import DialogActions from '@material-ui/core/DialogActions';
import Backdrop from '@material-ui/core/Backdrop';
import { makeStyles } from '@material-ui/core/styles';
import { Btn } from '../../nui';
import { loc } from '../../local';

const useStyles = makeStyles(theme => ({
    backdrop: {
        zIndex: theme.zIndex.drawer + 1,
        color: '#fff',
    },
}));

const DlgOrg = ({ open, title, hcmd, children, width="sm", fullWidth=true }) => (
    <Dialog
        maxWidth={width}
        keepMounted
        disableEscapeKeyDown
        fullWidth={fullWidth}
        onClose={(event, reason) => {
            if (reason !== 'backdropClick') {
                hcmd();
            }
        }}
        open={open}>
        <DialogTitle>{title}</DialogTitle>
        {children}
    </Dialog>
);

const DlgBase = ({ open, hcmd, title, children, action, width="sm", fullWidth=true }) => (
    <DlgOrg open={open} hcmd={hcmd} title={title} width={width} fullWidth={fullWidth}>
        <div className="mx-6">
            {children}
        </div>
        <DialogActions>
            {action}
        </DialogActions>
    </DlgOrg>
);

const Dlg = ({ open, hcmd, title, children, hcancel, width="sm", labcancel, labok, fullWidth=true, name=""}) => {
    const id_cancel = "dlgcancel" + name;
    const id_ok = "dlgclose" + name;

    const Cancel = () => {
        const desok = labok ? labok : loc("qd");

        if (hcancel) {
            return (
                <div>
                    <Btn hcmd={hcancel} name={id_cancel}>{labcancel ? labcancel : loc("qxi")}</Btn>
                    <Btn className="ml-8 mr-4" hcmd={hcmd} name={id_ok}>{desok}</Btn>
                </div>
            );
        }

        return <Btn hcmd={hcmd} name={id_ok}>{desok}</Btn>;
    };

    return <DlgBase open={open} hcmd={hcmd} title={title} children={children} hcancel={hcancel} action={<Cancel/>} width={width} fullWidth={fullWidth}/>;
};

const WaitDlg = ({ wrong, wait, hwait }) => {
    const classes = useStyles();

    return (
        <div>
            <Dlg title={loc("cw")} open={wrong ? true : false} hcmd={hwait}>
                <Alert severity="error" className="text-1xl mb-4">{wrong}</Alert>
            </Dlg>
            <Backdrop className={classes.backdrop} open={wait}>
                <CircularProgress color="inherit" />
            </Backdrop>
        </div>
    );
};

const WaitUmd = ({ umd }) => <WaitDlg wrong={umd.wrong} wait={umd.wait} hwait={umd.endWait}/>;

const ErrView = ({ err }) => {
    if (err) {
        return <Alert severity="error" className="text-1xl my-4">{err}</Alert>;
    }

    return null;
};

export {DlgBase, WaitUmd, ErrView, WaitDlg, Dlg};
